package skiree.host.abetsy.api.service.impl;

import cn.hutool.core.convert.Convert;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.ToString;
import org.apache.commons.lang3.time.DurationFormatUtils;
import org.springframework.stereotype.Component;
import skiree.host.abetsy.api.dao.AnimeDao;
import skiree.host.abetsy.api.dao.CommentDao;
import skiree.host.abetsy.api.dao.EpisodeDao;
import skiree.host.abetsy.api.service.CommentService;
import skiree.host.abetsy.api.vessel.Result;
import skiree.host.abetsy.model.LocalAnime;
import skiree.host.abetsy.model.LocalComment;
import skiree.host.abetsy.model.LocalEpisode;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

@Component
public class CommentServiceImpl implements CommentService {

    @Resource
    private CommentDao commentDao;

    @Resource
    private EpisodeDao episodeDao;

    @Resource
    private AnimeDao animeDao;

    @Override
    public Result list(int episodeId, String query, int pageNum, int pageSize) {
        // 分页信息
        Page<LocalComment> page = new Page<>(pageNum, pageSize);
        QueryWrapper<LocalComment> commentQuery = new QueryWrapper<>();
        commentQuery.eq("episode_id", episodeId);
        commentQuery.like("m", query);
        commentQuery.orderByAsc("t");
        IPage<LocalComment> commentPage = commentDao.selectPage(page, commentQuery);
        Map<String, Object> data = new HashMap<>();
        data.put("total", commentPage.getTotal());
        data.put("pageNum", pageNum);
        data.put("pageSize", pageSize);
        data.put("comment", parallelBarrage(commentPage.getRecords()));
        return Result.success(data);
    }

    @Override
    public Result shows(int episodeId) {
        //查询显示的标题
        QueryWrapper<LocalEpisode> episodeQuery = new QueryWrapper<>();
        episodeQuery.eq("id", episodeId);
        LocalEpisode localEpisode = episodeDao.selectOne(episodeQuery);
        String shows = "";
        if (localEpisode != null) {
            QueryWrapper<LocalAnime> animeQuery = new QueryWrapper<>();
            animeQuery.eq("id", localEpisode.getAnimeId());
            LocalAnime localAnime = animeDao.selectOne(animeQuery);
            if (localAnime != null) {
                shows = localAnime.getTitle() + " 第" + Convert.numberToChinese(localAnime.getSeason(), false)
                        + "季 第" + Convert.numberToChinese(localEpisode.getEpisodeIndex(), false) + "集";
            }
        }
        Map<String, Object> data = new HashMap<>();
        data.put("shows", shows);
        return Result.success(data);
    }

    private List<Barrage> parallelBarrage(List<LocalComment> records) {
        List<Barrage> barrageList = new ArrayList<>();
        for (LocalComment record : records) {
            barrageList.add(commentToBarrage(record));
        }
        return barrageList.stream()
                .sorted(Comparator.comparing(Barrage::getTime))
                .collect(Collectors.toList());
    }

    private Barrage commentToBarrage(LocalComment comment) {
        Barrage barrage = new Barrage();
        long time = comment.getT().multiply(new BigDecimal(1000)).longValue();
        barrage.setTime(DurationFormatUtils.formatDuration(time, "HH:mm:ss.SS").substring(0, 11));
        barrage.setId(comment.getCid());
        barrage.setText(comment.getM());
        try {
            String[] strings = comment.getP().split(",");
            int colorInt = Integer.parseInt(strings[2]);
            barrage.setColor(convertToHexColor(colorInt));
        } catch (Exception e) {
            barrage.setColor("#FFFFFF");
        }
        return barrage;
    }

    public static String convertToHexColor(int colorValue) {
        String hexString = Integer.toHexString(colorValue);
        if (hexString.length() < 6) {
            hexString = String.format("%6s", hexString).replace(' ', '0');
        } else if (hexString.length() > 6) {
            hexString = hexString.substring(0, 6);
        }
        return "#" + hexString.toUpperCase();
    }

    @Data
    @ToString
    @AllArgsConstructor
    @NoArgsConstructor
    static class Barrage {
        private Integer id;
        private String time;
        private String text;
        private String color;
    }

}
